import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
import 'package:flutter/rendering.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        initialRoute: "/", //名为"/"的路由作为应用的home(首页)
        theme: ThemeData(
          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
          useMaterial3: true,
        ),
        // home: const MyHomePage(title: 'Flutter Demo Home Page'),
        routes: {
          "/": (context) => const MyHomePage(title: '首页'), //注册首页路由
          "new_route": (context) => const NewRoute(),
          "tip_route": (context) => const TipRoute(),
          "tap_box_a": (context) => const TapBoxA(),
          "counter_widget": (context) => const CounterWidget(),
          "getState_object_route": (context) => const GetStateObjectRoute(),
          "button_route": (context) => const ButtonRoute(),
          "text_route": (context) => const TextRoute(),
          "picture_route": (context) => const PictureRoute(),
          "switch_route": (context) => const SwitchRoute(),
          "input_route": (context) => const InputRoute(),
          "schedule_route": (context) => const ScheduleRoute(),
          "padding_route": (context) => const PaddingRoute(),
          "ContainerRoute": (context) => const ContainerRoute(),
          "FittedBoxRoute": (context) => const FittedBoxRoute(),
          "ScaffoldRoute": (context) => const ScaffoldRoute(),
          "SingleChildScrollViewRoute": (context) =>
              const SingleChildScrollViewRoute(),
          "ListViewRoute": (context) => const ListViewRoute(),
          "ScrollControllerTestRoute": (context) =>
              const ScrollControllerTestRoute(),
          "ScrollNotificationTestRoute": (context) =>
              const ScrollNotificationTestRoute(),
          "AnimatedListRoute": (context) => const AnimatedListRoute(),
          "GridViewRoute": (context) => const GridViewRoute(),
          "PageViews": (context) => const PageViews(),
          "TabViewRoute1": (context) => const TabViewRoute1(),
          "TabViewRoute2": (context) => const TabViewRoute2(),
          "FlutterSliver": (context) => const FlutterSliver(),
          "NestedTabBarView1": (context) => const NestedTabBarView1(),
          "WillPopScopeTestRoute": (context) => const WillPopScopeTestRoute(),
        });
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String _text = '未获取参数';

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  void _setText(value) {
    // 判断类型错误，错误赋值‘参数类型错误’
    if (value is! String) value = '参数类型错误';
    setState(() {
      _text = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: SingleChildScrollView(
            child: Center(
                child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              '你已经点击了:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
            TextButton(
              child: const Text(
                '打开新界面',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context,
                    'new_route'); // 替代 Navigator.push(context, MaterialPageRoute(builder: (context) => NewRoute()));
              },
            ),
            TextButton(
              child: const Text(
                '打开传递参数界面',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () async {
                var result = await Navigator.pushNamed(context, 'tip_route',
                    arguments: {"text": '传递的参数'});
                _setText(result);
              },
            ),
            const Text(
              '当前参数:',
            ),
            Text(
              '$_text',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
            TextButton(
              child: const Text(
                '打开Widget管理自身状态',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'tap_box_a');
              },
            ),
            TextButton(
              child: const Text(
                '管理状态and生命周期',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'counter_widget');
              },
            ),
            TextButton(
              child: const Text(
                '通过Context获取State 对象',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'getState_object_route');
              },
            ),
            TextButton(
              child: const Text(
                '文本界面',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'text_route');
              },
            ),
            TextButton(
              child: const Text(
                '按钮界面',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'button_route');
              },
            ),
            TextButton(
              child: const Text(
                '图片界面',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'picture_route');
              },
            ),
            TextButton(
              child: const Text(
                '单选、多选界面',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'switch_route');
              },
            ),
            TextButton(
              child: const Text(
                '输入框、表单界面',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'input_route');
              },
            ),
            TextButton(
              child: const Text(
                'loading、进度条界面',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'schedule_route');
              },
            ),
            TextButton(
              child: const Text(
                'padding、装饰容器、transform',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'padding_route');
              },
            ),
            TextButton(
              child: const Text(
                '容器组件（Container）、剪裁（Clip）',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'ContainerRoute');
              },
            ),
            TextButton(
              child: const Text(
                '空间适配（FittedBox）',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'FittedBoxRoute');
              },
            ),
            TextButton(
              child: const Text(
                '页面骨架（Scaffold）',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'ScaffoldRoute');
              },
            ),
            TextButton(
              child: const Text(
                '可滚动组件SingleChildScrollView',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'SingleChildScrollViewRoute');
              },
            ),
            TextButton(
              child: const Text(
                '滚动分页组件（Scaffold）ListViewRoute',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'ListViewRoute');
              },
            ),
            TextButton(
              child: const Text(
                '滚动监听及控制',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'ScrollControllerTestRoute');
              },
            ),
            TextButton(
              child: const Text(
                '滚动监听',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'ScrollNotificationTestRoute');
              },
            ),
            TextButton(
              child: const Text(
                'AnimatedListRoute',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'AnimatedListRoute');
              },
            ),
            TextButton(
              child: const Text(
                '网格布局',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'GridViewRoute');
              },
            ),
            TextButton(
              child: const Text(
                'PageViews',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'PageViews');
              },
            ),
            TextButton(
              child: const Text(
                '顶部tabBar',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'TabViewRoute1');
              },
            ),
            TextButton(
              child: const Text(
                '顶部tabBar2',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'TabViewRoute2');
              },
            ),
            TextButton(
              child: const Text(
                'Flutter 中常用的 Sliver',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'FlutterSliver');
              },
            ),
            TextButton(
              child: const Text(
                'NestedTabBarView1',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'NestedTabBarView1');
              },
            ),
            TextButton(
              child: const Text(
                'WillPopScopeTestRoute导航拦截，点击两次返回后返回上一个页面',
                style: TextStyle(
                  color: Colors.blueAccent,
                  fontSize: 20,
                  decoration: TextDecoration.underline,
                  // 设置下划线颜色
                  decorationColor: Colors.blueAccent,
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'WillPopScopeTestRoute');
              },
            ),
          ],
        ))),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: '数字加1',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class NewRoute extends StatelessWidget {
  const NewRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("New route"),
      ),
      body: const Center(
        child: Text("This is new route"),
      ),
    );
  }
}

class TipRoute extends StatelessWidget {
  const TipRoute({super.key});

  String getText(Map args) {
    return args['text'] ?? '';
  }

  @override
  Widget build(BuildContext context) {
    // 获取路由参数
    var args = ModalRoute.of(context)!.settings.arguments;
    return Scaffold(
      appBar: AppBar(
        title: const Text('路由传参'),
      ),
      body: Padding(
          padding: const EdgeInsets.all(18.0),
          child: Center(
            child: Column(
              children: [
                Text(getText(args as Map)),
                ElevatedButton(
                  onPressed: () => Navigator.pop(context, '新参数***********'),
                  child: const Text('返回'),
                )
              ],
            ),
          )),
    );
  }
}

// 打开Widget管理自身状态
class TapBoxA extends StatefulWidget {
  const TapBoxA({super.key});

  @override
  State<TapBoxA> createState() => _TapBoxAState();
}

class _TapBoxAState extends State<TapBoxA> {
  bool _active = false;
  void _handleTap() {
    setState(() {
      _active = !_active;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: _handleTap,
        child: Container(
            child: Center(
          child: Text(_active ? 'active' : 'Inactive',
              style: const TextStyle(fontSize: 32.0, color: Colors.white)),
        )));
  }
}

// 管理状态and生命周期
class CounterWidget extends StatefulWidget {
  const CounterWidget({Key? key, this.initValue = 0});

  final int initValue;

  @override
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    //初始化状态
    _counter = widget.initValue;
    print("initState");
  }

  @override
  Widget build(BuildContext context) {
    print("build");
    return Scaffold(
      body: Center(
        child: TextButton(
          child: Text('$_counter'),
          //点击后计数器自增
          onPressed: () => setState(
            () => ++_counter,
          ),
        ),
      ),
    );
  }

  @override
  void didUpdateWidget(CounterWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    print("didUpdateWidget ");
  }

  @override
  void deactivate() {
    super.deactivate();
    print("deactivate");
  }

  @override
  void dispose() {
    super.dispose();
    print("dispose");
  }

  @override
  void reassemble() {
    super.reassemble();
    print("reassemble");
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print("didChangeDependencies");
  }
}

// 通过Context获取State 对象
class GetStateObjectRoute extends StatefulWidget {
  const GetStateObjectRoute({super.key});

  @override
  State<GetStateObjectRoute> createState() => _GetStateObjectRouteState();
}

class _GetStateObjectRouteState extends State<GetStateObjectRoute> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("子树中获取State对象"),
      ),
      body: Center(
        child: Column(
          children: [
            Builder(builder: (context) {
              return ElevatedButton(
                onPressed: () {
                  // 查找父级最近的Scaffold对应的ScaffoldState对象
                  ScaffoldState _state =
                      context.findAncestorStateOfType<ScaffoldState>()!;
                  // 打开抽屉菜单
                  _state.openDrawer();
                },
                child: const Text('打开抽屉菜单1'),
              );
            }),
            Builder(builder: (context) {
              return ElevatedButton(
                onPressed: () {
                  // 直接通过of静态方法来获取ScaffoldState
                  ScaffoldState _state = Scaffold.of(context);
                  // 打开抽屉菜单
                  _state.openDrawer();
                },
                child: const Text('打开抽屉菜单2'),
              );
            }),
            Builder(builder: (context) {
              return ElevatedButton(
                onPressed: () {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text("我是SnackBar")),
                  );
                },
                child: const Text('显示SnackBar'),
              );
            }),
          ],
        ),
      ),
      drawer: const Drawer(),
    );
  }
}

// 文字样式
class TextRoute extends StatelessWidget {
  const TextRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("文本界面"),
      ),
      body: const Center(
          child: Column(children: [
        Text(
          "Text",
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 20,
          ),
        ),
        Text(
          "Hello world",
          textAlign: TextAlign.left,
        ),
        Text(
          "Hello world! I'm Jack. ",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        Text(
          "Hello world",
          textScaleFactor: 1.5,
        ),
        Text(
          "TextStyle",
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 20,
          ),
        ),
        Text(
          "Hello world",
          style: TextStyle(
              color: Colors.blue,
              fontSize: 18.0,
              height: 1.2,
              fontFamily: "Courier",
              // background: Colors.accents,
              decoration: TextDecoration.underline,
              decorationStyle: TextDecorationStyle.dashed),
        ),
      ])),
    );
  }
}

// 按钮
class ButtonRoute extends StatelessWidget {
  const ButtonRoute({super.key});

  void _noOp() {}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("按钮界面"),
      ),
      body: Center(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                '按钮界面:',
              ),
              ElevatedButton(
                onPressed: () {},
                child: const Text('ElevatedButton'),
              ),
              TextButton(
                child: const Text("TextButton"),
                onPressed: () {},
              ),
              OutlinedButton(
                child: const Text("OutlinedButton"),
                onPressed: () {},
              ),
              IconButton(
                icon: const Icon(Icons.thumb_up),
                onPressed: () {},
              ),
              ElevatedButton.icon(
                icon: const Icon(Icons.send),
                label: const Text("发送"),
                onPressed: () {},
              ),
              OutlinedButton.icon(
                icon: const Icon(Icons.add),
                label: const Text("添加"),
                onPressed: () {},
              ),
              TextButton.icon(
                icon: const Icon(Icons.info),
                label: const Text("详情"),
                onPressed: () {},
              ),
            ]),
      ),
      floatingActionButton: FloatingActionButton(
        tooltip: '数字加1',
        child: const Icon(Icons.add),
        onPressed: () {},
      ),
    );
  }
}

// 图片界面
class PictureRoute extends StatelessWidget {
  const PictureRoute({super.key});

// https://img.zcool.cn/community/01df8e586c662fa801219c776e3923.jpg@3000w_1l_0o_100sh.jpg
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("图片界面"),
        ),
        body: Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
              // const Image({
              //   ...
              //   this.width, //图片的宽
              //   this.height, //图片高度
              //   this.color, //图片的混合色值
              //   this.colorBlendMode, //混合模式
              //   this.fit,//缩放模式
              //   this.alignment = Alignment.center, //对齐方式
              //   this.repeat = ImageRepeat.noRepeat, //重复方式
              //   ...
              // })
              // 加载该图片
              const Image(image: AssetImage("images/1.png"), width: 100.0),
              // Image也提供了一个快捷的构造函数Image.asset用于从asset中加载、显示图片：
              Image.asset(
                "images/1.png",
                width: 100.0,
              ),
              // 从网络加载图片
              const Image(
                image: NetworkImage(
                    "https://img.zcool.cn/community/01df8e586c662fa801219c776e3923.jpg@3000w_1l_0o_100sh.jpg"),
                width: 100.0,
              ),
              // Image也提供了一个快捷的构造函数Image.network用于从网络加载、显示图片：
              Image.network(
                "https://img.zcool.cn/community/01df8e586c662fa801219c776e3923.jpg@3000w_1l_0o_100sh.jpg",
                width: 100.0,
              ),
              const Text(
                '使用Material Design字体图标',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
              ),
              const Text(
                "\uE03e \uE237 \uE287",
                style: TextStyle(
                  fontFamily: "MaterialIcons",
                  fontSize: 24.0,
                  color: Colors.green,
                ),
              ),
              const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Icon(Icons.accessible, color: Colors.green),
                  Icon(Icons.error, color: Colors.green),
                  Icon(Icons.fingerprint, color: Colors.green),
                ],
              ),
              const Text(
                '使用自定义字体图标',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
              ),
              // fonts:
              // - family: myIcon  #指定一个字体名
              //   fonts:
              //     - asset: fonts/iconfont.ttf
            ])));
  }
}

// 单选、多选界面
class SwitchRoute extends StatefulWidget {
  const SwitchRoute({super.key});

  @override
  State<SwitchRoute> createState() => _SwitchRoute();
}

class _SwitchRoute extends State<SwitchRoute> {
  bool _switchSelected = true; //维护单选开关状态
  bool _checkboxSelected = true; //维护复选框状态

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: [
            const Text('是否确认呢'),
            Switch(
                value: _switchSelected,
                onChanged: (value) {
                  setState(() {
                    _switchSelected = value;
                  });
                }),
            const Text("女"),
            Checkbox(
                value: _checkboxSelected,
                activeColor: Colors.red, //选中时的颜色
                onChanged: (value) {
                  setState(() {
                    _checkboxSelected = value!;
                  });
                })
          ],
        ),
      ),
    );
  }
}

// 输入框、表单界面
class InputRoute extends StatelessWidget {
  const InputRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("输入框、表单界面"),
      ),
      body: const Center(
        child: Column(
          children: [
            TextField(
              autofocus: true,
              decoration: InputDecoration(
                  labelText: "用户名",
                  hintText: "用户名或邮箱",
                  prefixIcon: Icon(Icons.person)),
            ),
            TextField(
              decoration: InputDecoration(
                  labelText: "密码",
                  hintText: "您的登录密码",
                  prefixIcon: Icon(Icons.lock)),
              obscureText: true,
            ),
          ],
        ),
      ),
    );
  }
}

// loading、进度条界面
class ScheduleRoute extends StatefulWidget {
// class ScheduleRoute extends StatelessWidget {
  const ScheduleRoute({super.key});

  // StatelessWidget无状态的组件
  // @override
  // Widget build(BuildContext context) {
  //   return Scaffold(
  //     appBar: AppBar(
  //       title: const Text("loading、进度条界面"),
  //     ),
  //     body: Center(
  //         child: Column(
  //       children: [
  //         // 模糊进度条(会执行一个动画)
  //         LinearProgressIndicator(
  //           backgroundColor: Colors.grey[200],
  //           valueColor: const AlwaysStoppedAnimation(Colors.blue),
  //         ),
  //         //进度条显示50%
  //         LinearProgressIndicator(
  //           backgroundColor: Colors.grey[200],
  //           valueColor: const AlwaysStoppedAnimation(Colors.blue),
  //           value: .5,
  //         ),
  //         // 模糊进度条(会执行一个旋转动画)
  //         CircularProgressIndicator(
  //           backgroundColor: Colors.grey[200],
  //           valueColor: const AlwaysStoppedAnimation(Colors.blue),
  //         ),
  //         //进度条显示50%，会显示一个半圆
  //         CircularProgressIndicator(
  //           backgroundColor: Colors.grey[200],
  //           valueColor: const AlwaysStoppedAnimation(Colors.blue),
  //           value: .5,
  //         ),
  //         // 线性进度条高度指定为3
  //         SizedBox(
  //           height: 3,
  //           child: LinearProgressIndicator(
  //             backgroundColor: Colors.grey[200],
  //             valueColor: const AlwaysStoppedAnimation(Colors.blue),
  //             value: .5,
  //           ),
  //         ),
  //         // 圆形进度条直径指定为100
  //         SizedBox(
  //           height: 100,
  //           width: 100,
  //           child: CircularProgressIndicator(
  //             backgroundColor: Colors.grey[200],
  //             valueColor: const AlwaysStoppedAnimation(Colors.blue),
  //             value: .7,
  //           ),
  //         ),
  //         // 宽高不等
  //         SizedBox(
  //           height: 100,
  //           width: 130,
  //           child: CircularProgressIndicator(
  //             backgroundColor: Colors.grey[200],
  //             valueColor: AlwaysStoppedAnimation(Colors.blue),
  //             value: .7,
  //           ),
  //         ),
  //       ],
  //     )),
  //   );
  // }

  // StatefulWidget方式使用状态
  @override
  State<ScheduleRoute> createState() => _ScheduleRoute();
}

class _ScheduleRoute extends State<ScheduleRoute>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  @override
  void initState() {
    //动画执行时间3秒
    _animationController = AnimationController(
      vsync: this, //注意State类需要混入SingleTickerProviderStateMixin（提供动画帧计时/触发器）
      duration: const Duration(seconds: 3),
    );
    _animationController.forward();
    _animationController.addListener(() => setState(() => {}));
    super.initState();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(16),
            child: LinearProgressIndicator(
              backgroundColor: Colors.grey[200],
              valueColor: ColorTween(begin: Colors.grey, end: Colors.blue)
                  .animate(_animationController), // 从灰色变成蓝色
              value: _animationController.value,
            ),
          ),
        ],
      ),
    );
  }
}

// padding、装饰容器、transform
class PaddingRoute extends StatelessWidget {
  const PaddingRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return Padding(
      //上下左右各添加16像素补白
      padding: const EdgeInsets.all(16),
      child: Column(
        //显式指定对齐方式为左对齐，排除对齐干扰
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          const Padding(
            //左边添加8像素补白
            padding: EdgeInsets.only(left: 8),
            child: Text("only left 8"),
          ),
          const Padding(
            //上下各添加8像素补白
            padding: EdgeInsets.symmetric(vertical: 8),
            child: Text("上下各添加8像素补白,symmetric对称，vertical垂直"),
          ),
          const Padding(
            // 分别指定四个方向的补白
            padding: EdgeInsets.fromLTRB(20, 60, 20, 20),
            child: Text("分别指定四个方向的补白"),
          ),
          DecoratedBox(
              decoration: BoxDecoration(
                  gradient: const LinearGradient(colors: [
                    Colors.red,
                    Color.fromARGB(255, 243, 125, 8)
                  ]), //背景渐变
                  borderRadius: BorderRadius.circular(3.0), //3像素圆角
                  boxShadow: const [
                    //阴影
                    BoxShadow(
                        color: Colors.black54,
                        offset: Offset(2.0, 2.0),
                        blurRadius: 4.0)
                  ]),
              child: const Padding(
                padding: EdgeInsets.symmetric(horizontal: 80.0, vertical: 18.0),
                child: Text(
                  "装饰容器",
                  style: TextStyle(color: Colors.white),
                ),
              )),
          Container(
            color: Colors.black,
            child: Transform(
              alignment: Alignment.topRight, //相对于坐标系原点的对齐方式
              transform: Matrix4.skewY(0.3), //沿Y轴倾斜0.3弧度
              child: Container(
                padding: const EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),
                color: Colors.deepOrange,
                child: const Text('Y轴倾斜0.3弧度'),
              ),
            ),
          ),
          DecoratedBox(
            decoration: const BoxDecoration(color: Colors.red),
            //默认原点为左上角，左移20像素，向上平移5像素
            child: Transform.translate(
              offset: const Offset(-20.0, -5.0),
              child: const Text("原点为左上角，左移20像素，向上平移5像素"),
            ),
          ),
          DecoratedBox(
            decoration: const BoxDecoration(color: Colors.red),
            child: Transform.rotate(
              //旋转90度
              angle: math.pi / 2,
              child: const Text("旋转90度"),
            ),
          ),
          DecoratedBox(
              decoration: const BoxDecoration(color: Colors.red),
              child: Transform.scale(
                  scale: 1.5, //放大到1.5倍
                  child: const Text("放大到1.5倍"))),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              DecoratedBox(
                  decoration: const BoxDecoration(color: Colors.red),
                  child: Transform.scale(
                      scale: 1.5, child: const Text("Hello world"))),
              const Text(
                "你好",
                style: TextStyle(color: Colors.green, fontSize: 18.0),
              )
            ],
          ),
          const Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              DecoratedBox(
                decoration: BoxDecoration(color: Colors.red),
                //将Transform.rotate换成RotatedBox
                child: RotatedBox(
                  quarterTurns: 1, //旋转90度(1/4圈)
                  child: Text("Hello world"),
                ),
              ),
              Text(
                "你好",
                style: TextStyle(color: Colors.green, fontSize: 18.0),
              )
            ],
          ),
        ],
      ),
    );
  }
}

class MyClipper extends CustomClipper<Rect> {
  @override
  Rect getClip(Size size) => const Rect.fromLTWH(10.0, 15.0, 40.0, 30.0);

  @override
  bool shouldReclip(CustomClipper<Rect> oldClipper) => false;
}

// 容器组件（Container）
class ContainerRoute extends StatelessWidget {
  const ContainerRoute({super.key});

  @override
  Widget build(BuildContext context) {
    // 头像
    Widget avatar = Image.asset("images/1.png", width: 60.0);
    return Scaffold(
      body: Center(
          child: Column(children: [
        Container(
          margin: const EdgeInsets.only(top: 50.0, left: 120.0),
          constraints:
              const BoxConstraints.tightFor(width: 200.0, height: 150.0), //卡片大小
          decoration: const BoxDecoration(
            //背景装饰
            gradient: RadialGradient(
              //背景径向渐变
              colors: [Colors.red, Colors.orange],
              center: Alignment.topLeft,
              radius: .98,
            ),
            boxShadow: [
              //卡片阴影
              BoxShadow(
                color: Colors.black54,
                offset: Offset(2.0, 2.0),
                blurRadius: 4.0,
              )
            ],
          ),
          transform: Matrix4.rotationZ(.2), //卡片倾斜变换
          alignment: Alignment.center, //卡片内文字居中
          child: const Text(
            //卡片文字
            "5.20", style: TextStyle(color: Colors.white, fontSize: 40.0),
          ),
        ),
        const Text("剪裁（Clip）",
            style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold)),
        avatar, //不剪裁
        ClipOval(child: avatar), //剪裁为圆形
        ClipRRect(
          //剪裁为圆角矩形
          borderRadius: BorderRadius.circular(5.0),
          child: avatar,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Align(
              alignment: Alignment.topLeft,
              widthFactor: .5, //宽度设为原来宽度一半，另一半会溢出
              child: avatar,
            ),
            const Text(
              "你好世界",
              style: TextStyle(color: Colors.green),
            )
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ClipRect(
              //将溢出部分剪裁
              child: Align(
                alignment: Alignment.topLeft,
                widthFactor: .5, //宽度设为原来宽度一半
                child: avatar,
              ),
            ),
            const Text("你好世界", style: TextStyle(color: Colors.green))
          ],
        ),
        const Text("自定义裁剪（CustomClipper）",
            style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold)),
        DecoratedBox(
          decoration: const BoxDecoration(color: Colors.red),
          child: ClipRect(
              clipper: MyClipper(), //使用自定义的clipper
              child: avatar),
        )
      ])),
    );
  }
}

// 空间适配（FittedBox）
class FittedBoxRoute extends StatelessWidget {
  const FittedBoxRoute({super.key});

  String getText(int number) {
    var text = 'XX';
    for (var i = 0; i < number; i++) {
      text += 'XX';
    }
    return text;
  }

  Widget wContainer(BoxFit boxFit) {
    return Container(
      width: 50,
      height: 50,
      color: Colors.red,
      child: FittedBox(
        fit: boxFit,
        // 子容器超过父容器大小
        child: Container(width: 60, height: 70, color: Colors.blue),
      ),
    );
  }

  // 直接使用Row
  Widget wRow(String text) {
    Widget child = Text(text);
    child = Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [child, child, child],
    );
    return child;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Column(
              children: [
        const Text('空间适配（FittedBox）'),
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 30.0),
          child: Row(children: [
            FittedBox(
              fit: BoxFit.fitWidth,
              child: Text(getText(100)),
            )
          ]), //文本长度超出 Row 的最大宽度会溢出
        ),
        wContainer(BoxFit.none),
        const Text('Wendux'),
        wContainer(BoxFit.contain),
        const Text('Flutter中国'),
        const Text('实例：单行缩放布局'),
        wRow(' 90000000000000000 '),
        FittedBox(child: wRow(' 90000000000000000 ')),
        wRow(' 800 '),
        FittedBox(child: wRow(' 800 ')),
      ]
                  .map((e) => Padding(
                        padding: const EdgeInsets.symmetric(vertical: 20),
                        child: e,
                      ))
                  .toList())),
    );
  }
}

// 页面骨架（Scaffold）
class ScaffoldRoute extends StatefulWidget {
  const ScaffoldRoute({super.key});

  @override
  State<ScaffoldRoute> createState() => _ScaffoldRouteState();
}

class _ScaffoldRouteState extends State<ScaffoldRoute> {
  int _selectedIndex = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        //导航栏
        title: const Text("App Name"),
        actions: <Widget>[
          //导航栏右侧菜单
          IconButton(icon: const Icon(Icons.share), onPressed: () {}),
        ],
      ),
      drawer: const MyDrawer(), //抽屉
      bottomNavigationBar: BottomNavigationBar(
        // 底部导航
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
          BottomNavigationBarItem(
              icon: Icon(Icons.business), label: 'Business'),
          BottomNavigationBarItem(icon: Icon(Icons.school), label: 'School'),
        ],
        currentIndex: _selectedIndex,
        fixedColor: Colors.blue,
        onTap: _onItemTapped,
      ),
      floatingActionButton: FloatingActionButton(
          //悬浮按钮
          onPressed: _onAdd,
          //悬浮按钮
          child: const Icon(Icons.add)),
    );
  }

  void _onItemTapped(int index) {
    print('index: $index');
    setState(() {
      _selectedIndex = index;
    });
  }

  void _onAdd() {}
}

class MyDrawer extends StatelessWidget {
  const MyDrawer({super.key});

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: MediaQuery.removePadding(
        context: context,
        //移除抽屉菜单顶部默认留白
        removeTop: true,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(top: 38.0),
              child: Row(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16.0),
                    child: ClipOval(
                      child: Image.asset(
                        "images/1.png",
                        width: 80,
                      ),
                    ),
                  ),
                  const Text(
                    "Wendux",
                    style: TextStyle(fontWeight: FontWeight.bold),
                  )
                ],
              ),
            ),
            Expanded(
              child: ListView(
                children: const <Widget>[
                  ListTile(
                    leading: Icon(Icons.add),
                    title: Text('Add account'),
                  ),
                  ListTile(
                    leading: Icon(Icons.settings),
                    title: Text('Manage accounts'),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 可滚动组件SingleChildScrollView
class SingleChildScrollViewRoute extends StatelessWidget {
  const SingleChildScrollViewRoute({super.key});

  @override
  Widget build(BuildContext context) {
    String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    return Scaffold(
        appBar: AppBar(
          title: const Text('SingleChildScrollView'),
        ),
        body: SingleChildScrollView(
            child: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: Center(
            child: Column(
              //动态创建一个List<Widget>
              children: str
                  .split("")
                  //每一个字母都用一个Text显示,字体为原来的两倍
                  .map((c) => Text(
                        c,
                        textScaleFactor: 2.0,
                      ))
                  .toList(),
            ),
          ),
        )));
  }
}

// 滚动分页组件（Scaffold）
class ListViewRoute extends StatefulWidget {
  const ListViewRoute({super.key});

  @override
  State<ListViewRoute> createState() => _ListViewRoute();
}

class _ListViewRoute extends State<ListViewRoute> {
  static const loadingTag = "##loading##"; //表尾标记
  final _words = <String>[loadingTag];

  @override
  void initState() {
    super.initState();
    _retrieveData();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      itemCount: _words.length,
      itemBuilder: (context, index) {
        //如果到了表尾
        if (_words[index] == loadingTag) {
          //不足100条，继续获取数据
          if (_words.length - 1 < 200) {
            //获取数据
            _retrieveData();
            //加载时显示loading
            return Container(
              padding: const EdgeInsets.all(16.0),
              alignment: Alignment.center,
              child: const SizedBox(
                width: 24.0,
                height: 24.0,
                child: CircularProgressIndicator(strokeWidth: 2.0),
              ),
            );
          } else {
            //已经加载了100条数据，不再获取数据。
            return Container(
              alignment: Alignment.center,
              padding: const EdgeInsets.all(16.0),
              child: const Text(
                "没有更多了",
                style: TextStyle(color: Colors.grey),
              ),
            );
          }
        }
        // return ListTile(title: Text(_words[index]));
        return Text(_words[index],
            style: const TextStyle(color: Colors.green, fontSize: 16));
      },
      separatorBuilder: (context, index) => const Divider(height: .0),
    );
  }

  void _retrieveData() {
    Future.delayed(const Duration(seconds: 2)).then((e) {
      setState(() {
        //重新构建列表
        _words.insertAll(
          _words.length - 1,
          //每次生成20个单词
          generateWordPairs().take(20).map((e) => e.asPascalCase).toList(),
        );
      });
    });
  }
}

class ScrollControllerTestRoute extends StatefulWidget {
  const ScrollControllerTestRoute({super.key});

  @override
  ScrollControllerTestRouteState createState() {
    return ScrollControllerTestRouteState();
  }
}

class ScrollControllerTestRouteState extends State<ScrollControllerTestRoute> {
  final ScrollController _controller = ScrollController();
  bool showToTopBtn = false; //是否显示“返回到顶部”按钮

  @override
  void initState() {
    super.initState();
    //监听滚动事件，打印滚动位置
    _controller.addListener(() {
      print(_controller.offset); //打印滚动位置
      if (_controller.offset < 1000 && showToTopBtn) {
        setState(() {
          showToTopBtn = false;
        });
      } else if (_controller.offset >= 1000 && showToTopBtn == false) {
        setState(() {
          showToTopBtn = true;
        });
      }
    });
  }

  @override
  void dispose() {
    //为了避免内存泄露，需要调用_controller.dispose
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("滚动控制")),
      body: Scrollbar(
        child: ListView.builder(
            itemCount: 100,
            itemExtent: 50.0, //列表项高度固定时，显式指定高度是一个好习惯(性能消耗小)
            controller: _controller,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text("$index"),
              );
            }),
      ),
      floatingActionButton: !showToTopBtn
          ? null
          : FloatingActionButton(
              child: const Icon(Icons.arrow_upward),
              onPressed: () {
                //返回到顶部时执行动画
                _controller.animateTo(
                  .0,
                  duration: const Duration(milliseconds: 200),
                  curve: Curves.ease,
                );
              }),
    );
  }
}

class ScrollNotificationTestRoute extends StatefulWidget {
  const ScrollNotificationTestRoute({super.key});

  @override
  State<ScrollNotificationTestRoute> createState() =>
      _ScrollNotificationTestRouteState();
}

class _ScrollNotificationTestRouteState
    extends State<ScrollNotificationTestRoute> {
  String _progress = "0%"; //保存进度百分比

  @override
  Widget build(BuildContext context) {
    return Scrollbar(
      //进度条
      // 监听滚动通知
      child: NotificationListener<ScrollNotification>(
        onNotification: (ScrollNotification notification) {
          double progress = notification.metrics.pixels /
              notification.metrics.maxScrollExtent;
          //重新构建
          setState(() {
            _progress = "${(progress * 100).toInt()}%";
          });
          print("BottomEdge: ${notification.metrics.extentAfter == 0}");
          return false;
          //return true; //放开此行注释后，进度条将失效
        },
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            ListView.builder(
                itemCount: 100,
                itemExtent: 50.0,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text("$index"),
                  );
                }),
            CircleAvatar(
              //显示进度百分比
              radius: 30.0,
              backgroundColor: Colors.black54,
              child:
                  Text(_progress, style: const TextStyle(color: Colors.white)),
            )
          ],
        ),
      ),
    );
  }
}

class AnimatedListRoute extends StatefulWidget {
  const AnimatedListRoute({super.key});

  @override
  State<AnimatedListRoute> createState() => _AnimatedListRouteState();
}

class _AnimatedListRouteState extends State<AnimatedListRoute> {
  var data = <String>[];
  int counter = 5;

  final globalKey = GlobalKey<AnimatedListState>();

  @override
  void initState() {
    for (var i = 0; i < counter; i++) {
      data.add('${i + 1}');
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        AnimatedList(
          key: globalKey,
          initialItemCount: data.length,
          itemBuilder: (
            BuildContext context,
            int index,
            Animation<double> animation,
          ) {
            //添加列表项时会执行渐显动画
            return FadeTransition(
              opacity: animation,
              child: buildItem(context, index),
            );
          },
        ),
        buildAddBtn(),
      ],
    );
  }

  // 创建一个 “+” 按钮，点击后会向列表中插入一项
  Widget buildAddBtn() {
    return Positioned(
      bottom: 30,
      left: 0,
      right: 0,
      child: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () {
          // 添加一个列表项
          data.add('${++counter}');
          // 告诉列表项有新添加的列表项
          globalKey.currentState!.insertItem(data.length - 1);
          print('添加 $counter');
        },
      ),
    );
  }

  // 构建列表项
  Widget buildItem(context, index) {
    String char = data[index];
    return Padding(
        padding: const EdgeInsets.all(16),
        child: Row(children: <Widget>[
          const Icon(Icons.tag),
          Text(char, style: const TextStyle(color: Colors.red, fontSize: 18.0)),
          IconButton(
            icon: const Icon(Icons.delete),
            color: Colors.red,
            // 点击时删除
            onPressed: () => onDelete(context, index),
          ),
        ]));
  }

  void onDelete(context, index) {
    showDialog(
      context: context,
      barrierDismissible: false, //点击弹窗以外背景是否取消弹窗
      builder: (context) {
        return AlertDialog(
          title: const Text("温馨提示！"),
          content: const Text("您确定要删除吗？"),
          actions: [
            TextButton(
              onPressed: () {
                //关闭弹窗
                Navigator.of(context).pop();
              },
              child: const Text("取消"),
            ),
            TextButton(
              onPressed: () {
                //关闭弹窗
                Navigator.of(context).pop();
                setState(() {
                  globalKey.currentState!.removeItem(
                    index,
                    (context, animation) {
                      // 删除过程执行的是反向动画，animation.value 会从1变为0
                      var item = buildItem(context, index);
                      print('删除 ${data[index]}');
                      data.removeAt(index);
                      // 删除动画是一个合成动画：渐隐 + 收缩列表项
                      return FadeTransition(
                        opacity: CurvedAnimation(
                          parent: animation,
                          //让透明度变化的更快一些
                          curve: const Interval(0.5, 1.0),
                        ),
                        // 不断缩小列表项的高度
                        child: SizeTransition(
                          sizeFactor: animation,
                          axisAlignment: 0.0,
                          child: item,
                        ),
                      );
                    },
                    duration: const Duration(milliseconds: 200), // 动画时间为 200 ms
                  );
                });
              },
              child: const Text("确定"),
            ),
          ],
        );
      },
    );
  }
}

class GridViewRoute extends StatelessWidget {
  const GridViewRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GridView'),
      ),
      body: GridView(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3, //横轴三个子widget
              childAspectRatio: 1.0 //宽高比为1时，子widget
              ),
          children: const <Widget>[
            Icon(Icons.ac_unit),
            Icon(Icons.airport_shuttle),
            Icon(Icons.all_inclusive),
            Icon(Icons.beach_access),
            Icon(Icons.cake),
            Icon(Icons.free_breakfast)
          ]),
    );
  }
}

// Tab 页面
class PageViewItem extends StatefulWidget {
  const PageViewItem({super.key, required this.text});

  final String text;

  @override
  State<PageViewItem> createState() => _PageState();
}

class _PageState extends State<PageViewItem> {
  @override
  Widget build(BuildContext context) {
    print("build ${widget.text}");
    return Center(child: Text("${widget.text}", textScaleFactor: 5));
  }
}

class PageViews extends StatelessWidget {
  const PageViews({super.key});

  @override
  Widget build(BuildContext context) {
    var children = <Widget>[];
    // 生成 6 个 Tab 页
    for (int i = 0; i < 6; ++i) {
      children.add(PageViewItem(text: '$i'));
    }

    return PageView(
      // scrollDirection: Axis.vertical, // 滑动方向为垂直方向
      children: children,
    );
  }
}

class TabViewRoute1 extends StatefulWidget {
  const TabViewRoute1({super.key});

  @override
  State<TabViewRoute1> createState() => _TabViewRoute1State();
}

class _TabViewRoute1State extends State<TabViewRoute1>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  List tabs = ["新闻", "历史", "图片"];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: tabs.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("App Name"),
        bottom: TabBar(
          controller: _tabController,
          tabs: tabs.map((e) => Tab(text: e)).toList(),
        ),
      ),
      body: TabBarView(
        //构建
        controller: _tabController,
        children: tabs.map((e) {
          return KeepAlive(
            keepAlive: true,
            child: Container(
              alignment: Alignment.center,
              child: Text(e),
            ),
          );
        }).toList(),
      ),
    );
  }

  @override
  void dispose() {
    // 释放资源
    _tabController.dispose();
    super.dispose();
  }
}

class TabViewRoute2 extends StatelessWidget {
  const TabViewRoute2({super.key});
  @override
  Widget build(BuildContext context) {
    List tabs = ["新闻", "历史", "图片"];
    return DefaultTabController(
      length: tabs.length,
      child: Scaffold(
        appBar: AppBar(
          title: const Text("App Name"),
          bottom: TabBar(
            tabs: tabs.map((e) => Tab(text: e)).toList(),
          ),
        ),
        body: TabBarView(
          //构建
          children: tabs.map((e) {
            return KeepAlive(
              keepAlive: true,
              child: Container(
                alignment: Alignment.center,
                child: Text(e, textScaleFactor: 5),
              ),
            );
          }).toList(),
        ),
      ),
    );
  }
}

class FlutterSliver extends StatelessWidget {
  const FlutterSliver({super.key});
  @override
  Widget build(BuildContext context) {
    // 因为本路由没有使用 Scaffold，为了让子级Widget(如Text)使用
    // Material Design 默认的样式风格,我们使用 Material 作为本路由的根。
    return Material(
      child: CustomScrollView(
        slivers: <Widget>[
          // AppBar，包含一个导航栏.
          SliverAppBar(
            pinned: true, // 滑动到顶端时会固定住
            expandedHeight: 250.0,
            flexibleSpace: FlexibleSpaceBar(
              title: const Text('上滑后出现标题'),
              background: Image.asset(
                "images/1.png",
                fit: BoxFit.cover,
              ),
            ),
          ),
          SliverPadding(
            padding: const EdgeInsets.all(8.0),
            sliver: SliverGrid(
              //Grid
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2, //Grid按两列显示
                mainAxisSpacing: 10.0,
                crossAxisSpacing: 10.0,
                childAspectRatio: 4.0,
              ),
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  //创建子widget
                  return Container(
                    alignment: Alignment.center,
                    color: Colors.cyan[100 * (index % 9)],
                    child: Text('grid item $index'),
                  );
                },
                childCount: 20,
              ),
            ),
          ),
          SliverFixedExtentList(
            itemExtent: 50.0,
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                //创建列表项
                return Container(
                  alignment: Alignment.center,
                  color: Colors.lightBlue[100 * (index % 9)],
                  child: Text('list item $index'),
                );
              },
              childCount: 20,
            ),
          ),
        ],
      ),
    );
  }
}

class NestedTabBarView1 extends StatelessWidget {
  const NestedTabBarView1({super.key});

  @override
  Widget build(BuildContext context) {
    final tabs = <String>['猜你喜欢', '今日特价', '发现更多'];
    // 构建 tabBar
    return DefaultTabController(
      length: tabs.length, // tab的数量.
      child: Scaffold(
        body: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              SliverOverlapAbsorber(
                handle:
                    NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                sliver: SliverAppBar(
                  title: const Text('商城'),
                  floating: true,
                  snap: true,
                  forceElevated: innerBoxIsScrolled,
                  bottom: TabBar(
                    tabs: tabs.map((String name) => Tab(text: name)).toList(),
                  ),
                ),
              ),
            ];
          },
          body: TabBarView(
            children: tabs.map((String name) {
              return Builder(
                builder: (BuildContext context) {
                  return CustomScrollView(
                    key: PageStorageKey<String>(name),
                    slivers: <Widget>[
                      SliverOverlapInjector(
                        handle: NestedScrollView.sliverOverlapAbsorberHandleFor(
                            context),
                      ),
                      const SliverPadding(
                        padding: EdgeInsets.all(8.0),
                        // sliver: buildSliverList(50),
                      ),
                    ],
                  );
                },
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

class WillPopScopeTestRoute extends StatefulWidget {
  const WillPopScopeTestRoute({super.key});

  @override
  WillPopScopeTestRouteState createState() {
    return WillPopScopeTestRouteState();
  }
}

class WillPopScopeTestRouteState extends State<WillPopScopeTestRoute> {
  DateTime? _lastPressedAt; //上次点击时间

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_lastPressedAt == null ||
            DateTime.now().difference(_lastPressedAt!) > const Duration(seconds: 1)) {
          //两次点击间隔超过1秒则重新计时
          _lastPressedAt = DateTime.now();
          return false;
        }
        return true;
      },
      child: Container(
        alignment: Alignment.center,
        child: const Text("1秒内连续按两次返回键退出"),
      ),
    );
  }
}